from django.shortcuts import render,HttpResponse
import random
from django import forms
from app01.models import UserInfo

# Create your views here.
from django.conf import settings
from utils.tencent.sms import send_sms_single
from django.core.validators import RegexValidator  # 引入正则验证
def send_sms(request):
    """发送短信
        对于模板id:
        通过网页传递过来tpl的类型
        ?tpl = login --> 840532
        ?tpl = register --> 840533
    """
    tpl = request.GET.get("tpl")
    template_id = settings.SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse("模板不存在")
    code = random.randrange(1000,9999)
    res = send_sms_single("18911075051", "840533", [code, ])
    if res.result == 0:
        HttpResponse("成功")
        print("发送成功", res)
    else:
        print(res.errmsg)
    return HttpResponse("发送失败")

class RegisterModelForm(forms.ModelForm):
    # 可以在次进行重写form中的字段
    # 添加确认密码，验证码等字段
    password = forms.CharField(label="密码", widget=forms.PasswordInput())
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput())
    code = forms.CharField(label="验证码", widget=forms.TextInput())
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r"1[3|4|5|6|7|8|9]\d{9}$","手机号格式错误"),])

    class Meta:
        model = UserInfo
        fields = ["username", "email", "password", "confirm_password", "mobile_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs["class"] = "form-control"
            field.widget.attrs["placeholder"] = "请输入%s" % field.label


def register(request):
    form = RegisterModelForm()
    return render(request, "app01/register.html", {"form":form})


